package org.firebug.spring.boot.metadata.api;

import org.firebug.common.bean.api.Meta;
import org.firebug.common.bean.api.Response;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {HttpMessageNotReadableException.class})
    Response handle400(HttpMessageNotReadableException e) {
        return Response.newInstance(Meta._400, e.getMessage());
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    Response handle400(MethodArgumentNotValidException e) {
        Map<String, Object> map = new HashMap();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            map.put(error.getField(), error.getDefaultMessage());
        }
        return Response.newInstance(Meta._400, map);
    }

    @ExceptionHandler(value = {UnsatisfiedServletRequestParameterException.class})
    Response handle400(UnsatisfiedServletRequestParameterException e) {
        return Response.newInstance(Meta._400, e.getMessage());
    }

    @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
    Response handle405(HttpRequestMethodNotSupportedException e) {
        return Response.newInstance(Meta._405, e.getMessage());
    }

//    @ExceptionHandler(value = {RuntimeException.class})
//    Response handle400(RuntimeException e) {
//        return Response.newInstance(Meta._400, e.getMessage());
//    }
//
//    @ExceptionHandler(value = {Exception.class})
//    Response handle500(Exception e) {
//        return Response.newInstance(Meta._500, e.getMessage());
//    }
}